package com.heima.wemedia.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/*全局配置：如需不同的消息指定不同的消息发送确认机制，可单独在消息发送时指定*/
@Configuration
@Slf4j
public class RabbitConfig implements InitializingBean {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("初始化 RabbitTemplate 的配置，设置发送确认机制和消息返还机制");
        /*设置消息转换器*/
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        /*设置发送消息确认*/
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            /*correlationData[异步回调数据，Message]、isACK[发送方消息确认结果]、claus[消息发送失败的原因]*/
            public void confirm(CorrelationData correlationData, boolean isACK, String cause) {
                if (isACK) {
                    log.info("交换机成功接收到消息"); //消息发布到交换机后，其消息确认回调不会返回【消息】
                } else {
                    log.error("消息未能成功发送到指定交换机, 当前消息 id: {}", correlationData.getReturnedMessage().getMessageProperties().getDeliveryTag());
                }
                //TODO: 消息发送到交换机的途中出现异常，导致没有回执
                //TODO: 扩展自动重试

            }
        });
        /*设置消息返还机制*/
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.error("交换机路由当前消息到目标队列失败，应答码: {}，应答内容: {}，交换机: {}，路由 key: {}，消息: {}", replyCode, replyText, exchange, routingKey, message);
            }
        });
    }

}
